package com.cqrcb.cloud.service.quota.base;

import com.cqrcb.cloud.entity.api.req.Q;
import com.cqrcb.cloud.entity.api.req.RequestHeader;
import com.cqrcb.cloud.entity.api.res.R;
import com.cqrcb.cloud.entity.constant.MarketConstant;
import com.cqrcb.cloud.entity.quota.CustomerMultiQuotaCtrlDetail;
import com.cqrcb.cloud.entity.quota.MultiQuotaLog;
import com.cqrcb.cloud.entity.quota.io.CustomerMultiQuotaCtrlMarketMainIO;
import com.cqrcb.cloud.entity.quota.io.base.QuotaBaseIO;
import com.cqrcb.cloud.service.quota.MultiQuotaLogService;
import com.cqrcb.cloud.service.quota.QuotaBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author ：29520
 * @date ：Created in 2021/6/25 8:53
 * @description：
 * @modified By：
 * @version:
 */
@Slf4j
public abstract class QuotaBaseServiceImpl implements QuotaBaseService {

    @Autowired
    private MultiQuotaLogService multiQuotaLogService;

    @Override
    public <T extends QuotaBaseIO> R deductionFinancialProductQuota(String type, Q<T> recordq, Class<T> tClass){
        log.info("进入维护额度信息->");
        T record = recordq.getBody();
        RequestHeader header = recordq.getHeader();

        int status = MarketConstant.STATUS_SUCCESS;
        String statusDesc = MarketConstant.STATUS_SUCCESS_STR;
        MultiQuotaLog multiQuotaLog = null;

        Object customerMultiQuotaCtrlDetails = null;
        try {
            log.info("正在记录额度流水->");
            //记录扣减流水到DB
            Object t = getMultiQuotaCtrlMarketMainForRedis(record);
            multiQuotaLog = multiQuotaLogService.buildMainLogAndSaveDB(header,type,record,t);
            log.info("正在维护额度信息->");
            //额度扣减的核心逻辑
            customerMultiQuotaCtrlDetails = deductionFinancialProductQuotaCore(record);
            log.info("额度维护成功->");
        }catch (Exception e){
            log.error("额度维护失败，原因->{}",e);
            status = MarketConstant.STATUS_FAIL;
            statusDesc = e.toString();
            throw e;
        }finally {
            log.info("正在维护额度流水->");
            //修改扣减流水
            multiQuotaLogService.updateMultiQuotaLog(multiQuotaLog,customerMultiQuotaCtrlDetails,status,statusDesc);
        }
        return R.data(customerMultiQuotaCtrlDetails);
    }
}
